package com.pomelo.tiku.managers;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * @author liuxiangwang
 * @date .
 */
public class SharedPreferenceManager {
    private static SharedPreferenceManager instance;
    private static final String FILE_NAME = "pomelo"; //文件名
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private  static Context mContext;

    private SharedPreferenceManager() {
        sharedPreferences = mContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public static SharedPreferenceManager getInstance(Context context) {
        if(instance == null) {
            synchronized (SharedPreferenceManager.class) {
                if(instance == null) {
                    mContext = context;
                    instance = new SharedPreferenceManager();
                }
            }
        }
        return instance;
    }
    /**
     * 存入键值对
     * @param key
     * @param value
     */

    public void save(String key, Object value){
        //判断类型
        String type = value.getClass().getSimpleName();
        if("Integer".equals(type)){
            editor.putInt(key,(Integer)value);
        }else if ("Boolean".equals(type)){
            editor.putBoolean(key,(Boolean)value);
        }else if ("Float".equals(type)){
            editor.putFloat(key,(Float)value);
        }else if ("Long".equals(type)){
            editor.putLong(key,(Long)value);
        }else if ("String".equals(type)){
            editor.putString(key,(String) value);
        }
        editor.apply();
    }

    /**
     * 读取键的值，若无则返回默认值
     * @param key
     * @param defValue 默认值
     * @return
     */
    public Object get(String key, Object defValue){
        String type = defValue.getClass().getSimpleName();
        if("Integer".equals(type)){
            return sharedPreferences.getInt(key,(Integer)defValue);
        }else if ("Boolean".equals(type)){
            return sharedPreferences.getBoolean(key,(Boolean)defValue);
        }else if ("Float".equals(type)){
            return sharedPreferences.getFloat(key,(Float)defValue);
        }else if ("Long".equals(type)){
            return sharedPreferences.getLong(key,(Long)defValue);
        }else if ("String".equals(type)){
            return sharedPreferences.getString(key,(String) defValue);
        }
        return null;
    }

    /**
     * 清除所有数据
     */
    public void clear() {
        editor.clear();
        editor.commit(); // 提交更改
    }

}
